package com.seo.utils;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;

import org.apache.commons.lang3.StringUtils;

/**
 * 自定义工具类
 * 
 * @author Administrator
 * @version 2017.12.01 11:40
 */
public class CustomUtil {

	/**
	 * 生成固定长度随机数
	 * 
	 * @param length length
	 * @return 返回随机数
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static int buildRandom(int length) {
		int num = 1;
		double random = Math.random();
		if (random < 0.1) {
			random = random + 0.1;
		}
		for (int i = 0; i < length; i++) {
			num = num * 10;
		}
		return (int) ((random * num));
	}

	/**
	 * 后缀
	 * 
	 * @param length length
	 * @param id     id
	 * @return 返回后缀
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static String codeSuf(int length, int id) {

		DecimalFormat dfHead = new DecimalFormat("0000");
		String formatStr = dfHead.format(id);
		String tempStr = StringUtils.substring(formatStr, formatStr.length() - 4);
		String str = buildRandom(length) + tempStr;

		return str;
	}

	/**
	 * 隐藏手机号
	 * 
	 * @param phone phone
	 * @return 返回隐藏手机号
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static String subPhone(String phone) {
		return phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4, phone.length());
	}

	/**
	 * 获取id
	 * 
	 * @param code      code
	 * @param preLength preLength
	 * @param sufLength sufLength
	 * @return 返回id
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static int getId(String code, int preLength, int sufLength) {
		String res = StringUtils.substring(code, preLength, code.length() - sufLength);

		return Integer.parseInt(res);
	}

	/**
	 * 获取code
	 * 
	 * @param code code
	 * @param id   id
	 * @return 返回code
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static String getCode(String code, int id) {
		String res = StringUtils.substring(code, 0, 4) + id
				+ StringUtils.substring(code, code.length() - 7, code.length());

		return res;
	}

	/**
	 * 获取订单code
	 * 
	 * @param length length
	 * @param id     id
	 * @return 返回code
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static String orderCode(int length, int id) {

		DecimalFormat dfHead = new DecimalFormat("0000");
		String formatStr = dfHead.format(id);
		String tempStr = StringUtils.substring(formatStr, formatStr.length() - 4);
		String str = DateUtil.getYear() + buildRandom(length) + tempStr;

		return str;
	}

	/**
	 * 获取订单code
	 * 
	 * @param length length
	 * @param id     id
	 * @param userId userId
	 * @return 返回code
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static String orderCode(int length, long id, int userId) {
		StringBuffer sb = new StringBuffer();
		DecimalFormat dfHead = new DecimalFormat("0000");
		String formatStr = dfHead.format(userId);
		String tempStr = StringUtils.substring(formatStr, formatStr.length() - 4);
		int random = buildRandom(length);
		String ids = String.valueOf(id + StringUtils.length(id + "") * random);
		sb.append(ids).append(random).append(tempStr);

		return sb.toString();
	}

	/**
	 * toReplaceSpec
	 * 
	 * @param spec spec
	 * @param from from
	 * @param to   to
	 * @return 返回值
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static String toReplaceSpec(String spec, String from, String to) {
		if (StringUtils.isEmpty(spec)) {
			return "0";
		} else {
			return spec.replaceAll(from, to);
		}

	}

	/**
	 * 停止线程
	 * 
	 * @param minTime minTime
	 * @param maxTime maxTime
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static void sleep(int minTime, int maxTime) {
		try {
			Random rand = new Random();
			int sleepTime = rand.nextInt(maxTime - minTime) + minTime;
			Thread.sleep(sleepTime);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public static int random(int minTime, int maxTime) {
		Random rand = new Random();
		return rand.nextInt(maxTime - minTime) + minTime;
	}

	/**
	 * String转int
	 * 
	 * @param str str
	 * @return 返回int
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static int strToInt(String str) {
		try {
			if (StringUtils.isEmpty(str)) {
				return 0;
			} else {
				return Integer.parseInt(str);
			}
		} catch (Exception e) {
			return 0;
		}

	}

	/**
	 * 元转换成分
	 * 
	 * @param currency currency
	 * @return 返回值
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static String getMoney(BigDecimal currency) {
		if (currency == null) {
			return "";
		}
		BigDecimal res = currency.multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_DOWN);

		return res.toString();
	}

	/**
	 * 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。
	 * 
	 * @param params params
	 * @param key    key
	 * @return 返回值
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static String createSign(Map<String, String> params, String key) {
		StringBuffer sb = new StringBuffer();
		Set es = params.entrySet();
		Iterator it = es.iterator();
		sb.append("{");
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
				sb.append('"' + k + '"' + ":" + '"' + v + '"' + ",");
			}
		}
		sb.append('"' + "key" + '"' + ":" + "\"" + key + "\"");
		sb.append("}");
		System.out.println(sb.toString());
		String sign = MD5Util.MD5Encode(sb.toString(), "utf-8").toUpperCase();
		return sign;
	}

	/**
	 * 创建sha1摘要,规则是:签名参数按照字段名的ASCII
	 * 码从小到大排序（字典序）后，使用URL键值对的格式（即key1=value1&key2=value2…）拼接。
	 * 
	 * @param params params
	 * @return 返回值
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static String createPublicSign(Map<String, String> params) {
		StringBuffer sb = new StringBuffer();
		Set<Entry<String, String>> es = params.entrySet();
		Iterator<Entry<String, String>> it = es.iterator();
		while (it.hasNext()) {
			Map.Entry<String, String> entry = it.next();
			String k = entry.getKey();
			String v = entry.getValue();
			if (StringUtils.isNotEmpty(v) && !"sign".equals(k) && !"key".equals(k)) {
				sb.append(k).append("=").append(v).append("&");
			}
		}
		String str = sb.substring(0, sb.length() - 1);
		try {
			// SHA1签名生成
			MessageDigest md = MessageDigest.getInstance("SHA-1");
			md.update(str.getBytes());
			byte[] digest = md.digest();

			StringBuffer hexstr = new StringBuffer();
			String shaHex = "";
			for (int i = 0; i < digest.length; i++) {
				shaHex = Integer.toHexString(digest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexstr.append(0);
				}
				hexstr.append(shaHex);
			}
			return hexstr.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 生成URL链接
	 * 
	 * @param params params
	 * @return 返回值
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static String createUrl(Map<String, String> params) {
		StringBuffer sb = new StringBuffer();
		Set<Entry<String, String>> es = params.entrySet();
		Iterator<Entry<String, String>> it = es.iterator();
		while (it.hasNext()) {
			Map.Entry<String, String> entry = it.next();
			String k = entry.getKey();
			String v = entry.getValue();
			if (StringUtils.isNotEmpty(v)) {
				sb.append(k).append("=").append(v).append("&");
			}
		}
		return sb.toString();
	}

	/**
	 * 生成token
	 * 
	 * @param loginId loginId
	 * @param key     key
	 * @return 返回Token
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static String makeUserToken(int loginId, String key) {
		String nonce = ShortUrlUtil.buildCode(8);
		String timestamp = Long.toString(System.currentTimeMillis());
		Map<String, String> params = new TreeMap<String, String>();
		params.put("loginId", Integer.toString(loginId));
		params.put("nonce", nonce);
		params.put("timestamp", timestamp);
		String userToken = CustomUtil.createSign(params, key);
		return userToken;
	}

	/**
	 * 生成token
	 * 
	 * @param userId userId
	 * @param key    key
	 * @return 返回Token
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static String makeUserToken(String userId, String key) {
		String nonce = ShortUrlUtil.buildCode(8);
		String timestamp = Long.toString(System.currentTimeMillis());
		Map<String, String> params = new TreeMap<String, String>();
		params.put("userId", userId);
		params.put("nonce", nonce);
		params.put("timestamp", timestamp);
		String userToken = CustomUtil.createSign(params, key);
		return userToken;
	}

	/**
	 * getStackTraceAsString
	 * 
	 * @param ex ex
	 * @return 返回值
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static String getStackTraceAsString(Throwable ex) {
		StringWriter stringWriter = new StringWriter();
		ex.printStackTrace(new PrintWriter(stringWriter));
		return stringWriter.toString();
	}

	/**
	 * 字母加数字随机
	 * 
	 * @param length length
	 * @return 返回值 String
	 * @author Administrator
	 * @version 2017.12.01 11:40
	 */
	public static String getStringRandom(int length) {

		String val = "";
		Random random = new Random();

		// 参数length，表示生成几位随机数
		for (int i = 0; i < length; i++) {

			String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
			// 输出字母还是数字
			if ("char".equalsIgnoreCase(charOrNum)) {
				// 输出是大写字母还是小写字母
				int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
				val += (char) (random.nextInt(26) + temp);
			} else if ("num".equalsIgnoreCase(charOrNum)) {
				val += String.valueOf(random.nextInt(10));
			}
		}
		return val;
	}

	public static void main(String args[]) {

		System.out.println("果园开始");
		String classId = "99";
		String nonce = "68872";
		String page = "1";
		String showNum = "6";
		String timestamp = "20180626201311040";
		System.out.println("果园开始111");
		String key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB";
		System.out.println("果园key:" + key);
		Map map = new TreeMap();
		map.put("classId", classId);
		map.put("nonce", nonce);
		map.put("page", page);
		map.put("showNum", showNum);
		map.put("timestamp", timestamp);
		System.out.println("果园结束222:" + map);
		// String sign = Code.codeSign(map).toUpperCase();
		String sign = CustomUtil.createSign(map, key);
		System.out.println("果园结束2:" + sign);

	}
}
